#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
'''
@File    :   service.py
@Time    :   2024/02/22 16:12:44
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from typing import Any

from ninja_extra import ModelService
from ninja_extra.exceptions import APIException
from ninja_extra import service_resolver
from ninja_extra.controllers import RouteContext
from .schemas import CreateExamCategorySchema
from .models import ExamCategory


class ExamCategoryService(ModelService):
    def create(self, schema: CreateExamCategorySchema, **kwargs: Any) -> Any:
        context: RouteContext = service_resolver(RouteContext)
        if not ExamCategory.objects.filter(tag=schema.tag).exists():
            data = schema.dict(by_alias=True)
            data["creator"]=context.request.user
            data.update(kwargs)
            instance = self.model._default_manager.create(**data)
            return instance
        raise APIException("考试分类tag已存在")
    
    def update(self, instance: Any, schema: CreateExamCategorySchema,**kwargs: Any) -> Any:
        """
        Args:
            instance (Any): 对象实例。
            schema: CreateExamCategorySchema。
            **kwargs (Any): 关键字参数。
        Returns:
            Any: 对象实例。
        Raises:
            Exception: 如果实例为空。
        Examples:
            >>> instance = SomeClass()
            >>> instance.update(name='John', age=25)
            >>> instance.save()
        """
        context: RouteContext = service_resolver(RouteContext)
        if not instance:
            raise Exception("需要传入实例")
        if not ExamCategory.objects.filter(tag=schema.tag).exists() or instance.tag==schema.tag:
            data = schema.dict(exclude_none=True)
            data["modifier"]=context.request.user.username
            data.update(kwargs)
            for attr, value in data.items():
                setattr(instance, attr, value)
            instance.save()
            return instance
        raise APIException("考试分类tag已存在")